//
//  PacketCenter.m
//  QBIM
//
//  Created by liunian on 14-3-17.
//  Copyright (c) 2014年 liunian. All rights reserved.
//

#import "PacketCenter.h"
#import "ProtocolConfig.h"
#import "GCDAsyncSocket.h"
#import "DDLog.h"

#define FORMAT(format, ...) [NSString stringWithFormat:(format), ##__VA_ARGS__]

#define kReceivingTimeoutInterval   30
#define TAG_FIXED_LENGTH_HEADER     101
#define TAG_RESPONSE_BODY           102

@interface PacketCenter ()<GCDAsyncSocketDelegate> {
    GCDAsyncSocket *_socket;
}
- (void)setupConnection;
@property (nonatomic, retain) GCDAsyncSocket *socket;
@end

@implementation PacketCenter
@synthesize delegate = _delegate;
#pragma mark - class
- (id)init{
    if (self == [super init]) {
        [self setupConnection];
    }
    return self;
}

- (void)sendPacket:(NSData *)packet
{
	if ([packet length] == 0)
        {
        return;
        }
    
    [self getConnection];
    [_socket writeData:packet withTimeout:-1 tag:0];
//	[_socket readDataWithTimeout:-1 tag:0];
}
#pragma mark GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
    if ([self.delegate respondsToSelector:@selector(packetCenterDidConnectServer:)]) {
        [self.delegate packetCenterDidConnectServer:self];
    }
    [_socket readDataWithTimeout:-1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{
    if ([self.delegate respondsToSelector:@selector(packetCenter:didReceivedData:)]) {
        [self.delegate packetCenter:self didReceivedData:data];
    }
    [_socket readDataWithTimeout:-1 tag:0];
}


- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    //...
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    if ([self.delegate respondsToSelector:@selector(packetCenter:didDisconnectWithError:)]) {
        [self.delegate packetCenter:self didDisconnectWithError:err];
    }
}

#pragma mark
- (void)setupConnection {
    if (nil == _socket)
        _socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    [_socket setDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *error = nil;
    if (![_socket connectToHost:SERVER_DOMAIN_IM_SOCKET  onPort:kPort_IM_SOCKET error:&error]) {
        @throw [NSException exceptionWithName:@"GCDAsyncSocket"
                                       reason:[error localizedDescription]
                                     userInfo:nil];
    }
}

//判断是否是连接的状态
-(BOOL)isConnected {
    return _socket.isConnected;
}

//断开连接
-(void)disConnect{
    [_socket disconnect];
    _socket = nil;
}

//取得连接
-(void)getConnection {
    if (![_socket isConnected]) {
        [self disConnect];
        [self setupConnection];
    }
}

- (void)setDelegate:(id<PacketDelegate>)delegate{
    if (_delegate != delegate) {
        _delegate = delegate;
    }
}

@end
